<template>
  <!-- 该组件可成为动态添加tableData行的公共组件。
1. 参考线可配置（参考flat-map-points)
2. 提供两个维度的添加按钮,根据传值确定按钮文字（两维度：搜索biaxial 一维度：flat-map-points） -->
  <div>
    <div class="vs-btn-group">
      <el-button
        plain
        class="btn-sure"
        type="primary"
        size="default"
        icon="CirclePlus"
        :disabled="barAddDisable"
        @click.stop="addBar"
      >{{ button1Name }}</el-button>
      <el-button
        v-if="button2Name"
        plain
        class="btn-sure"
        type="primary"
        size="default"
        icon="CirclePlus"
        :disabled="lineAddDisable"
        @click.stop="addLine"
      >{{ button2Name }}</el-button>
    </div>
    <el-table :data="form.tableData" size="default" class="mapping-table" :tooltip-effect="xvueTheme">
      <el-table-column prop="field" :label="$demoi18n('panelData.mapping.field')" width="50">
        <template #default="scope">
          <span :title="scope.row.field">{{ scope.row.field }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$demoi18n('panelData.mapping.mapping')" min-width="120">
        <template #default="scope">
          <span v-if="!scope.row.skipVerification" class="mapping-scope">*</span>
          <VsFormItem
            :prop="`tableData[${scope.$index}].mapping`"
            :rules="
              generateExceptionRules({
                required: !scope.row.skipVerification,
                label: $demoi18n(scope.row.explain),
              })
            "
          >
            <!-- xTag 下拉项 -->
            <el-select
              v-if="form.dataSourceType === 'xTag'"
              v-model="scope.row.mapping"
              :class="'panel-data-select-' + xvueTheme"
              :popper-class="'select-poper-' + xvueTheme"
              filterable
              clearable
              placeholder
              size="default"
              @focus="setXtagMaxWidth"
              @visible-change="setTagTitle($event)"
              @change="xTagTableDataChange(scope.row)"
            >
              <el-option
                v-for="(item, index) in commonComp.mappingOptionsXTag"
                :key="item.id"
                class="panel-data-select-option"
                :label="item.option_label"
                :value="item.option_label"
                :style="selectxTagStyle"
              >
                <div
                  v-if="item.type && item.type === 'add'"
                  @click.stop="optionxTagClick(item, scope.row, 'fromChild')"
                >
                  <span class="select-option-slot-icon">
                    <el-button :link="true" type="primary" class="select-icon">
                      <el-icon><Plus /></el-icon>
                    </el-button>
                  </span>
                  <span
                    class="select-option-slot-text"
                    :style="{ width: `${xTagTextWidth}px` }"
                  >&nbsp;{{ item.option_label }}</span>
                </div>
                <div v-else-if="item.type && item.type === 'edit'">
                  <span class="select-option-slot-icon select-option-slot-icon-edit">
                    <el-button
                      :link="true"
                      type="primary"
                      class="select-icon"
                      :title="$demoi18n('btn.edit')"
                      @click.stop="optionxTagClick(item, scope.row, 'fromChild')"
                    >
                      <el-icon><EditPen /></el-icon>
                    </el-button>
                    <el-button
                      :link="true"
                      type="primary"
                      class="select-icon"
                      :title="$demoi18n('btn.delete')"
                      @click.stop="optionxTagDelete(index)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </span>
                  <span class="select-option-slot-text" :style="{ width: `${xTagTextWidth}px` }">{{
                    item.option_label
                  }}</span>
                </div>
                <div v-else>
                  <span>{{ item.option_label }}</span>
                </div>
              </el-option>
            </el-select>

            <!-- xMiner 下拉项 -->
            <el-select
              v-else
              v-model="scope.row.mapping"
              :class="'panel-data-select-' + xvueTheme"
              :popper-class="'select-poper-' + xvueTheme"
              filterable
              clearable
              placeholder
              size="default"
              @focus="setMaxWidth"
              @visible-change="setTagTitle($event)"
              @change="getApiData"
            >
              <el-option
                v-for="item in commonComp.mappingOptions"
                :key="item.id"
                class="panel-data-select-option"
                :label="item.option_label"
                :value="item.option_value"
                :style="selectStyle"
              >
                <div class="vs_ellipsis" :title="`${item.option_label} (${item.option_value})`">{{
                  item.option_label
                }}</div>
              </el-option>
            </el-select>
          </VsFormItem>
        </template>
      </el-table-column>
      <el-table-column
        v-if="legendColumnName"
        :label="legendColumnName"
        min-width="110"
        :render-header="renderTableHeader"
      >
        <template #default="scope">
          <VsFormItem
            :prop="`tableData[${scope.$index}].legendName`"
            :rules="
              generateRules({
                required: false,
                label: legendColumnName,
              })
            "
          >
            <el-input
              v-if="!scope.row.hideLegendName"
              v-model="scope.row.legendName"
              :placeholder="$demoi18n('word.plsInput')"
              size="default"
            ></el-input>
          </VsFormItem>
        </template>
      </el-table-column>
      <el-table-column
        v-if="isUnitShow"
        :label="$demoi18n('panel.th.indicatorUnit')"
        min-width="80"
        :render-header="renderTableHeader"
      >
        <template #default="scope">
          <VsFormItem
            :prop="`tableData[${scope.$index}].legendUnit`"
            :rules="
              generateRules({
                required: false,
                label: $demoi18n('word.unit'),
              })
            "
          >
            <el-input
              v-if="typeof scope.row.legendUnit === 'string'"
              v-model="scope.row.legendUnit"
              :placeholder="$demoi18n('word.plsInput')"
              size="default"
            ></el-input>
          </VsFormItem>
        </template>
      </el-table-column>
      <el-table-column
        prop="explain"
        :label="$demoi18n('panel.th.explain')"
        min-width="70"
        :render-header="renderTableHeader"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ $demoi18n(scope.row.explain) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$demoi18n('panel.th.operation')" width="40" :render-header="renderTableHeader">
        <template #default="scope">
          <el-button
            v-if="!scope.row.notShowDelete && (/^y\d+$/.test(scope.row.field) || scope.row.field.includes('z'))"
            icon="Delete"
            :link="true"
            type="primary"
            :disabled="!scope.row.isDelete"
            @click.stop="deleteCurRow(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="jsx">
import EventBus from '@/event-bus/EventBus.js';
import xTagBase from '../xtag-base.js';

/**
 * config  整体配置项
 * dataForm   初始表单的字段
 */
const xMiner = 'xMiner';
const xTag = 'xTag';
export default {
  name: 'PanelDataAddRow',
  mixins: [xTagBase],
  props: [
    'config',
    'widgetInstanceId',
    'dataForm',
    'dataSourceTypeOptions',
    'button1Name',
    'button2Name',
    'legendColumnName',
    'commonComp',
    'minAddLen',
  ],
  data() {
    return {
      xMiner,
      xTag,
      propertyData: this.property,
      form: {},
      count: {
        y: 0,
        z: 0,
      },
      barAddDisable: false,
      lineAddDisable: false,
      index: 0,
      isUnitShow: false,
      xTagTextWidth: 100,
      myMinAddLen: 1,
    };
  },
  computed: {},
  watch: {
    'form.tableData'() {
      this.initIndex();
    },
  },
  created() {
    this.form = this.dataForm;
    if (this.config) {
      const dataConfig = JSON.parse(JSON.stringify(this.config.config.data));
      this.initTableData(dataConfig.tableData);
      this.loadData(dataConfig);
    }

    // 切换数据映射表格后 重置this.count.y
    EventBus.$on('vs_reset_count_y', () => {
      this.count.y = 1;
    });
  },
  beforeUnmount() {
    EventBus.$off('vs_reset_count_y');
  },
  methods: {
    initTableData(tableData) {
      this.form.tableData = tableData;

      if (this.myMinAddLen >= 1) {
        for (let i = 1; i < this.count.y + this.index; i++) {
          if (this.form.tableData[i]) {
            this.form.tableData[i].isDelete = this.count.y !== 1;
          }
        }
        for (let i = this.count.y + this.index; i < this.form.tableData.length; i++) {
          if (this.form.tableData[i]) {
            this.form.tableData[i].isDelete = this.count.z !== 1;
          }
        }
        if (this.form.tableData[this.index]) {
          this.isUnitShow = typeof this.form.tableData[this.index].legendUnit === 'string';
        }
      }
    },

    /**
     * 初始化count和index
     */
    initIndex() {
      const { tableData } = this.form;
      const ynItems = tableData.filter(n => /^y\d+$/.test(n.field) );
      const znItems = tableData.filter(n => /^z\d+$/.test(n.field) );
      const y1Item = ynItems[0];
      this.count.y = ynItems.length;
      this.count.z = znItems.length;

      if (this.minAddLen !== null) {
        this.myMinAddLen = this.minAddLen;
      }
      this.index = tableData.includes(y1Item) ? tableData.indexOf(y1Item) : tableData.length;
    },

    addBar() {
      let addItem = {};

      const explainMap = {
        [`config_${process.env.xvueNameSpace_}biaxial_line_line`]: 'panel.label.leftAxis',
        [`config_${process.env.xvueNameSpace_}biaxial_line_bar`]: 'panelData.explain.leftAxisCylindrical',
      };
      const explain = explainMap[this.config.propertyPannelName] || 'panel.explain.showAttachedValue';

      // 热图暂时如此处理，如有新组件也有类似逻辑，则需要添加唯一标识
      if (this.myMinAddLen >= 1) {
        addItem = {
          field: `y${this.count.y + 1}`,
          mapping: '',
          legendName: '',
          explain: this.form.tableData[this.index].explain,
        };
      } else {
        addItem = {
          field: `y${this.count.y + 1}`,
          mapping: '',
          explain,
          skipVerification: true,
        };
      }

      if (this.isUnitShow) {
        addItem.legendUnit = '';
      }
      this.form.tableData.splice(this.count.y + this.index, 0, addItem);

      this.count.y++;
      for (let i = this.index; i < this.count.y + this.index; i++) {
        this.form.tableData[i].isDelete = true;
      }
    },
    addLine() {
      const len = this.form.tableData.length;
      this.form.tableData.push({
        field: `z${this.count.z + 1}`,
        mapping: '',
        legendName: '',
        explain: this.form.tableData[len - 1].explain,
      });
      this.count.z++;
      for (let i = this.count.y + this.index; i < this.form.tableData.length; i++) {
        this.form.tableData[i].isDelete = true;
      }
    },
    deleteCurRow(row) {
      const index = this.form.tableData.indexOf(row);
      this.form.tableData.splice(index, 1);

      if (row.field.includes('y')) {
        this.count.y--;
        for (let i = index; i < this.count.y + this.index; i++) {
          this.form.tableData[i].field = `y${i - this.index + 1}`;
        }

        if (this.myMinAddLen >= 1) {
          this.form.tableData[this.index].isDelete = this.count.y !== 1;
        }
      } else {
        this.count.z--;
        for (let i = index; i < this.form.tableData.length; i++) {
          this.form.tableData[i].field = `z${i - this.count.y}`;
        }

        this.form.tableData[this.count.y + this.index].isDelete = this.count.z !== 1;
      }
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
  },
};
</script>
<style lang="less" scoped>
.prop-form {
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

.vs-btn-group {
  padding: 10px 0 10px 10px;
}

.table-span {
  text-align: center;
}
:deep(.el-table) {
  .cell {
    padding: 0 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.option_item {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

<style lang="less">
.panel-data-select-dark {
  :deep(.el-input) {
    .el-input__inner {
      border-color: #588ba8;
      color: #fff;
      background-color: #091a2d;
    }
    .el-input__icon {
      color: #588ba8;
    }
  }
}

.select-poper-dark {
  background-color: #091a2d;
  border-color: #588ba8;

  :deep(.el-scrollbar) {
    .el-select-dropdown__list {
      .el-select-dropdown__item {
        padding: 0 12px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;
        color: #fff;
        background-color: #091a2d;

        .select-icon {
          margin-left: 0;
          padding: 0;
        }

        .select-option-slot-text {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #178ddf;
        }
        .select-option-slot-icon {
          display: inline-block;
          vertical-align: top;
        }
      }
      .hover {
        background-color: #102e4f;
      }
    }
  }
  :deep(.popper__arrow) {
    border-bottom-color: #588ba8;
    &::after {
      border-bottom-color: #091a2d !important;
    }
  }
}

.select-poper-light {
  :deep(.el-scrollbar) {
    .el-select-dropdown__list {
      .el-select-dropdown__item {
        padding: 0 12px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;
        .select-icon {
          margin-left: 0;
          padding: 0;
        }

        .select-option-slot-text {
          display: inline-block;

          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .select-option-slot-icon {
          display: inline-block;
          vertical-align: top;
        }
      }
    }
  }
}
</style>
